import Vue from 'vue'
import Router from 'vue-router'
import store from "../store"

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/login',
      component: resolve => require(['@/view/login.vue'], resolve)
    },
    {
      path: '/',
      redirect: '/admin'
    },
    {
      path: '/admin',
      meta: {
        requireAuth: true
      },
      component: resolve => require(['@/view/containerMain.vue'], resolve),
      children: [
        {
          path: '/',
          redirect: 'order'
        },
        {
          path: 'order',
          meta: {
            requireAuth: true
          },
          component: resolve => require(['@/view/order.vue'], resolve)
        },
        {
          path: 'loginHistory',
          meta: {
            requireAuth: true
          },
          component: resolve => require(['@/view/loginHistory.vue'], resolve)
        },
        {
          path: 'news',
          meta: {
            requireAuth: true
          },
          component: resolve => require(['@/view/news.vue'], resolve)

        },
        {
          path: 'advertising',
          meta: {
            requireAuth: true
          },
          component: resolve => require(['@/view/advertising.vue'], resolve)
        },
        {
          path: 'fcode',
          meta: {
            requireAuth: true
          },
          component: resolve => require(['@/view/fcode.vue'], resolve)
        },
        {
          path: 'addNews/:id',
          meta: {
            requireAuth: true
          },
          component: resolve => require(['@/view/addNews.vue'], resolve)
        },
        {
          path: 'preview/:id',
          component: resolve => require(['@/view/previewNews.vue'], resolve)
        },
        {
          path: 'userControl',
          component: resolve => require(['@/view/userControl.vue'], resolve)
        },
        {
          path: 'updatePassword',
          meta: {
            requireAuth: true
          },
          component: resolve => require(['@/view/updatePassword.vue'], resolve)
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.matched.length === 0) {                                        //如果未匹配到路由
    from.name ? next({name: from.name}) : next('/');   //如果上级也未匹配到路由则跳转登录页面，如果上级能匹配到则转上级路由
  } else {
    if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
      if (store.state.user.token) {  // 通过vuex state获取当前的token是否存在 || getCookie('token')
        next();
      } else {
        next({
          path: '/login',
          query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
        })
      }
    } else {
      next();
    }                                                                          //如果匹配到正确跳转
  }
})
export default router
